package cn.ichiva.conf;

import cn.ichiva.common.ThreadContent;
import cn.ichiva.common.jwt.DefaultJWTParser;
import cn.ichiva.common.jwt.JWTParser;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

@Configuration
public class TedisPlusApiConfig implements ApplicationContextAware{

    @Value("${public-key-path}")
    public String publicKey;

    @Bean
    public JWTParser getJWTParser() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        return new DefaultJWTParser(Files.readAllBytes(Paths.get(publicKey)));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBean(StringRedisTemplate.class)
                .setKeySerializer(new UserKeyRedisSerializer());
    }

    class UserKeyRedisSerializer implements RedisSerializer<String>{

        @Override
        public byte[] serialize(String key) throws SerializationException {
            Object account = ThreadContent.get("account");
            if(null != account){
                return String.format("%s:%s",account,key).getBytes(StandardCharsets.UTF_8);
            }
            throw new RuntimeException("非法");
        }

        @Override
        public String deserialize(byte[] bytes) throws SerializationException {
            Object args = ThreadContent.get("account");
            if(null != args){
                int len = args.toString().length() + 2;
                return new String(bytes,StandardCharsets.UTF_8).substring(len);
            }else {
                return new String(bytes,StandardCharsets.UTF_8);
            }
        }
    }
}
